<script setup lang="ts">
import {ref, reactive, onMounted, onUnmounted} from "vue";
import SvgIcon from "../Tool/svg-icon.vue";
import {LeiToolsBillDatabase, BillInterface} from "../../lib/database.ts";
import {ElMessage} from "element-plus";
import {save} from "@tauri-apps/plugin-dialog";

const database: LeiToolsBillDatabase = new LeiToolsBillDatabase("./sqlite.db")
const billTypes = {
    income: [
        {icon: 'wages', label: '工资'},
        {icon: 'red', label: '红包'},
        {icon: 'account', label: '转账'},
        {icon: 'gift', label: '礼物'},
    ],
    outcome: [
        {icon: 'food', label: '餐饮'},
        {icon: 'shopping', label: '购物'},
        {icon: 'travel', label: '出行'},
        {icon: 'clothes', label: '服饰'},
        {icon: 'entertainment', label: '娱乐'},
        {icon: 'study', label: '学习'},
        {icon: 'health', label: '医疗'},
        {icon: 'life', label: '家居'},
        {icon: 'phone', label: '话费'},
        {icon: 'electricity', label: '电费'},
        {icon: 'water', label: '水费'},
        {icon: 'gas', label: '燃气费'},
        {icon: 'book', label: '书籍'},
        {icon: 'car', label: '汽车'},
        {icon: 'gift', label: '礼物'},
    ]
}
const mode = ref(true)

onMounted(async () => {
    await database.open()
    await database.createTable()
    tableData.value = (await database.query()) as BillInterface[]
    console.log(tableData.value)
    tablePage.value = tableData.value.slice((pageCurrent.value - 1) * pageSize.value, pageCurrent.value * pageSize.value)
})

onUnmounted(async () => {
    await database.close()
    console.log('数据库已关闭')
})


const optionList = [
    {
        icon: 'add',
        label: '新建记录',
    }, {
        icon: 'modify',
        label: '修改记录',
    }, {
        icon: 'delete',
        label: '删除记录',
    }, {
        icon: 'download',
        label: '导出选中',
    }, {
        icon: 'upload',
        label: '导出全部',
    }
]
const drawerData = reactive<BillInterface>({
    datetime: (new Date()).toLocaleString(),
    label: '收入',
    money: 0,
    small: '工资',
    destination: '',
    remark: '',
})

const tableData = ref<BillInterface[]>([])
const pageSize = ref(15)
const pageCurrent = ref(1)
const drawer = ref(false)
const tableSelection = ref<BillInterface[]>([])

const tablePage = ref([])

const handleCurrentChange = (val: number) => {
    tablePage.value = tableData.value.slice((val - 1) * pageSize.value, val * pageSize.value)
}

const handleClick = async (label: string) => {
    if (label === 'add') {
        drawer.value = true
        drawerData.datetime = (new Date()).toLocaleString()
        mode.value = true
    }
    else if (label === 'modify') {
        // 打开drawer进行修改，只针对一条记录
        if (tableSelection.value.length !== 1) {
            ElMessage.warning('请选择一条记录进行修改')
            return
        }
        drawer.value = true
        mode.value = false
        console.log(tableSelection.value[0], mode.value)
        // 修改记录
        drawerData.datetime = tableSelection.value[0].datetime
        drawerData.label = tableSelection.value[0].label
        drawerData.money = tableSelection.value[0].money
        drawerData.small = tableSelection.value[0].small
        drawerData.destination = tableSelection.value[0].destination
        drawerData.remark = tableSelection.value[0].remark

    }
    else if (label === 'delete') {
        // 删除选择的记录
        for (let item of tableSelection.value) {
            await database.delete(`id = ${item.id}`)
        }
        // 更新表格数据
        tableData.value = (await database.query()) as BillInterface[]
        tablePage.value = tableData.value.slice((pageCurrent.value - 1) * pageSize.value, pageCurrent.value * pageSize.value)
        // 清空选择的记录
        tableSelection.value = []
        // 提示删除成功
        ElMessage.success('删除成功')
    }
    else if (label === 'download') {
        // 下载选中记录
        if (tableSelection.value.length === 0) {
            ElMessage.warning('请选择记录进行导出')
            return
        }
        const filepath = await save({
            title: '导出文件',
            defaultPath: 'bill.csv',
            filters: [{name: 'CSV', extensions: ['csv']}]
        })
        if (filepath === null) {
            ElMessage.warning('导出文件失败')
            return
        }
        // 导出文件TODO
    }
    else if (label === 'upload') {
        // 下载全部记录
        const filepath = await save({
            title: '导出文件',
            defaultPath: 'bill.csv',
            filters: [{name: 'CSV', extensions: ['csv']}]
        })
        if (filepath === null) {
            ElMessage.warning('导出文件失败')
            return
        }
        // 导出文件TODO
    }
}

const handleSubmit = async () => {
    if (mode.value) {
        // 新增记录
        if (await database.insert(drawerData) <= 0) {
            ElMessage.error('添加失败')
            return
        }
    } else {
        // 修改数据库表格数据
        await database.update(drawerData, `id = ${tableSelection.value[0].id}`)
    }
    // 提交数据
    tableData.value = (await database.query()) as BillInterface[]
    tablePage.value = tableData.value.slice((pageCurrent.value - 1) * pageSize.value, pageCurrent.value * pageSize.value)
    // 提示添加成功
    ElMessage.success(mode.value ? '添加成功' : '修改成功')
    drawer.value = false
}

const handleSelectionChange = (val: BillInterface[]) => {
    tableSelection.value = val
}

</script>

<template>
    <el-card style="height: calc(100% - 8px)" body-style="padding: 10px">
        <template #header>
            <el-row style="width: 100%;">
                <el-col :span="2">
                    <h3 style="margin: 0">账单记录</h3>
                </el-col>
                <el-col :span="22" style="display: flex; justify-content: flex-end;">
                    <el-tooltip
                        effect="dark"
                        :content="item.label"
                        placement="top"
                        v-for="item in optionList"
                    >
                        <el-button type="info" circle @click="handleClick(item.icon)">
                            <el-icon :size="25">
                                <svg-icon :name="item.icon" width="20px" height="20px"></svg-icon>
                            </el-icon>
                        </el-button>
                    </el-tooltip>
                </el-col>
            </el-row>
        </template>
        <el-table
            row-key="id"
            @selection-change="handleSelectionChange"
            :data="tablePage"
            stripe
            highlight-current-row
            style="width: 100%"
            table-layout="fixed">
            <el-table-column type="selection"/>
            <el-table-column prop="datetime" label="时间日期"/>
            <el-table-column prop="label" label="账单类型"/>
            <el-table-column prop="money" label="账单金额"/>
            <el-table-column prop="small" label="收支类型"/>
            <el-table-column prop="destination" label="资金流向"/>
            <el-table-column prop="remark" label="备注"/>
        </el-table>
        <el-pagination
            v-model:current-page="pageCurrent"
            v-model:page-size="pageSize"
            :page-sizes="[15]"
            size="default"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
            style="margin-top: 10px; display: flex; justify-content: center"
            @current-change="handleCurrentChange"
        />
        <el-drawer v-model="drawer"
                   title="添加账单"
                   :close-on-click-modal="false"
                   :with-header="true">
            <el-form
                label-position="right"
                label-width="auto"
            >
                <el-form-item label="时间日期" label-position="right" class="form-item">
                    <el-input v-model="drawerData.datetime" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="账单类别" label-position="right" class="form-item">
                    <el-select v-model="drawerData.label" placeholder="Select"
                               @change="drawerData.small = drawerData.label === '收入' ? '工资' : '餐饮'">
                        <el-option label="收入" value="收入"/>
                        <el-option label="支出" value="支出"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="账单金额" label-position="right" class="form-item">
                    <el-input v-model="drawerData.money" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="收支类型" label-position="right" class="form-item">
                    <template v-if="drawerData.label === '收入'">
                        <el-select v-model="drawerData.small" placeholder="Select">
                            <el-option
                                v-for="item in billTypes.income"
                                :label="item.label"
                                :value="item.label"
                            >
                                <div>
                                    <el-icon :size="16">
                                        <svg-icon :name="item.icon" width="20px" height="20px"></svg-icon>
                                    </el-icon>
                                    <span style="margin-left: 15px">{{ item.label }}</span>
                                </div>
                            </el-option>
                        </el-select>
                    </template>
                    <template v-else>
                        <el-select v-model="drawerData.small" placeholder="Select">
                            <el-option
                                v-for="item in billTypes.outcome"
                                :key="item.icon"
                                :label="item.label"
                                :value="item.label"
                            >
                                <div>
                                    <el-icon :size="16">
                                        <svg-icon :name="item.icon" width="20px" height="20px"></svg-icon>
                                    </el-icon>
                                    <span style="margin-left: 15px">{{ item.label }}</span>
                                </div>
                            </el-option>
                        </el-select>
                    </template>
                </el-form-item>
                <el-form-item label="资金流向" label-position="right" class="form-item">
                    <el-input v-model="drawerData.destination" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="备注" label-position="right" class="form-item">
                    <el-input type="textarea" v-model="drawerData.remark" autocomplete="off"/>
                </el-form-item>
                <el-form-item style="text-align: center;">
                    <div style="width: 100%; display: flex; justify-content: center">
                        <el-button type="primary" @click="handleSubmit" v-if="mode">
                            添加
                        </el-button>
                        <el-button type="primary" @click="handleSubmit" v-else>
                            修改
                        </el-button>
                        <el-button type="primary" @click="drawer = false; ElMessage.warning('添加失败')">取消</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>

<style scoped lang="css">

</style>